package com._51cto.healthy.security;

import com._51cto.healthy.pojo.User;
import com._51cto.healthy.service.UserService;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Component
public class SecurityUserDetailsService implements UserDetailsService {

    @DubboReference
    private UserService userService;
    @Autowired
    private HttpSession session;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //远程读取数据---这里需要读取用户信息【包括角色，权限，目录】
        User user = userService.getUserByUsername(username);
        session.setAttribute("userId",user.getId());
        //断言判断用户名
        Assert.notNull(user, "用户名密码错误！");
        //创建权限列表
        List<GrantedAuthority> auths = new ArrayList<>();
        //获取角色列表,遍历结果
        user.getRoles().forEach(role->{
            //添加角色权限
            auths.add(new SimpleGrantedAuthority(role.getKeyword()));
            //获取权限 -遍历权限列表
            role.getPermissions().forEach(permission ->
                    //添加权限
                    auths.add(new SimpleGrantedAuthority(permission.getKeyword())));
        });
        //创建安全用户
        //把获取到的数据库信息添加到SecurityUser
        UserDetails details = new SecurityUser(user.getId(),user.getUsername(),user.getPassword(),auths)
                .setAvatar(user.getAvatar())
                .setRoles(user.getRoles());
        return details;
    }
}
